package com.naiterui.ehp.bs.doctor.controller.inner;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotEmpty;

import com.naiterui.ehp.bp.constants.SwaggerTag;
import io.swagger.annotations.Api;
import org.apache.commons.codec.Charsets;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.naiterui.ehp.bp.bo.agent.DoctorDetailBO;
import com.naiterui.ehp.bp.support.exception.BusinessException;
import com.naiterui.ehp.bp.support.exception.PublicService;
import com.naiterui.ehp.bp.support.exception.ResponseVO;
import com.naiterui.ehp.bs.doctor.api.TencentApi;
import com.naiterui.ehp.bs.doctor.exception.ExceptionCodes;
import com.naiterui.ehp.bs.doctor.service.IDoctorService;
import com.naiterui.ehp.bs.doctor.service.ILoginService;
import com.naiterui.ehp.bs.doctor.vo.DoctorInfoExcelVO;
import com.naiterui.ehp.bs.doctor.vo.SignUserParamVO;
import com.naiterui.ehp.bs.doctor.vo.inner.DoctorParamVO;


@Validated
@RestController
@RequestMapping("ad/inner/doctor")
@Api(tags = {SwaggerTag.DOCTOR + SwaggerTag.INNER_API + SwaggerTag.DOCTOR_MANAGER})
public class AdInnerDoctorController {

    private static Logger LOGGER = LoggerFactory.getLogger(AdInnerDoctorController.class);

    @Autowired
    private IDoctorService doctorService;
    @Autowired
    private ILoginService loginService;

    @GetMapping("/{doctorId}/{status}")
    public ResponseVO<Void> accountStatus(@PathVariable("doctorId") Long doctorId,
        @PathVariable("status")
        @Max(value = 1, message = "状态不正确")
        @Min(value = 0, message = "状态不正确") Integer status,
        @RequestHeader("operator") String operator) {
        try {
            operator = URLDecoder.decode(operator, Charsets.UTF_8.name());
        } catch (UnsupportedEncodingException ignored) {
        }
        LOGGER.info("修改医生状态 请求参数：doctorId = {}, status = {} operator = {}", doctorId, status, operator);
        doctorService.updateAccountStatus(doctorId, status, operator);
        return PublicService.returnResponseVO(ExceptionCodes.SUCCESS);
    }

    @GetMapping("/{doctorId}/type")
    public ResponseVO<Void> accountType(@PathVariable("doctorId") Long doctorId,
        @Max(value = 1, message = "类别不正确")
        @Min(value = 0, message = "类别不正确") Integer type,
        @RequestHeader("operator") String operator) {
        try {
            operator = URLDecoder.decode(operator, Charsets.UTF_8.name());
        } catch (UnsupportedEncodingException ignored) {
        }
        LOGGER.info("修改医生账户类别 请求参数：doctorId = {}, type = {} operator = {}", doctorId, type, operator);
        doctorService.updateAccountType(doctorId, type, operator);
        return PublicService.returnResponseVO(ExceptionCodes.SUCCESS);
    }


    @PostMapping("/update")
    public ResponseVO<Void> update(@RequestBody DoctorParamVO doctorParamVO, @RequestHeader("operator") String operator) throws BusinessException {
        if (doctorParamVO == null || doctorParamVO.getDoctorId() == null) {
            throw new BusinessException(ExceptionCodes.PARAM_ERROR);
        }
        try {
            operator = URLDecoder.decode(operator, Charsets.UTF_8.name());
        } catch (UnsupportedEncodingException ignored) {
        }
        LOGGER.info("修改医生信息 请求参数：doctorParamVO = {}, operator = {}", doctorParamVO, operator);
        doctorService.updateDoctorInfo(doctorParamVO, operator);
        return PublicService.returnResponseVO(ExceptionCodes.SUCCESS);
    }

    /**
     * @param param {手机号}-姓名
     * @return
     */
    @PostMapping("dr/add")
    public ResponseVO<List<Long>> register(@NotEmpty String param) {
        LOGGER.info("后台创建医生 param:{}", param);
        List<Long> doctorIdList = new ArrayList<>();
        String[] arr = param.split(",");
        for (String u : arr) {
            String[] uArr = u.split("-");
            String phone = uArr[0];
            String name = uArr[1];
            String pwd = null;
            if (uArr.length > 2) {
                pwd = uArr[2];
            }
            try {
                Long doctorId = loginService.addUser(phone, name, pwd);
                doctorIdList.add(doctorId);
            } catch (BusinessException e) {
                LOGGER.warn("后台创建医生账户失败 user:{}", u, e.getMessage());
            }
        }
        return PublicService.returnResponseVO(ExceptionCodes.SUCCESS, doctorIdList);
    }

    @GetMapping("idcard/verify")
    public ResponseVO<Void> verifyIdCard(String idCard, String name) throws BusinessException {
        TencentApi.idCardVerification(1L, idCard, name);
        return PublicService.returnResponseVO(ExceptionCodes.SUCCESS);
    }

    /**
     * 发送待审核医生通知短信
     * 例如：12:00:00~12:30:00期间平台新增备案申请15个，请及时处理
     * @return
     * @throws BusinessException
     */
    @PostMapping("audit/doctor/notice")
    public ResponseVO<Void> sendAuditDoctorNotice() throws BusinessException {
        LOGGER.info("发送待审核医生通知短信");
        doctorService.sendAuditDoctorNotice();
        return PublicService.returnResponseVO(ExceptionCodes.SUCCESS);
    }

    /**
     * 保存登录信息
     * 
     * @param loctorInfos
     * @throws BusinessException
     */
    @PostMapping("/batchSaveDoctor")
    public void batchSaveDoctor(@RequestBody List<DoctorInfoExcelVO> doctorInfos) throws BusinessException {
        doctorService.batchSaveDoctor(doctorInfos);
    }

    /**
     * 保存证件号
     * 
     * @param doctorId
     * @param number
     * @param type
     *            类型：3.执业证 4.身份证 6.资格证
     * @return
     */
    @PostMapping("/saveNumber")
    public String saveNumber(Long doctorId, String number, Integer type) throws BusinessException {
        return doctorService.saveNumber(doctorId, number, type);
    }

    @GetMapping("/getUserByPhone")
    public SignUserParamVO getUserByPhone(String phone) throws BusinessException {
        return doctorService.getUserByPhone(phone);
    }

    @GetMapping("/getDetail")
    public DoctorDetailBO getUserCenter(Long doctorId) throws BusinessException {
        return doctorService.getDoctorDetailById(doctorId);
    }

}
